/**
 * Copyright (c) 2019 xstgongyi.org
 * All rights reserved.
 */
package org.xstgongyi.eduaid.service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xstgongyi.eduaid.auth.AuthHelper;
import org.xstgongyi.eduaid.dao.UserMapper;
import org.xstgongyi.eduaid.dataobject.UserDO;

/**
 * @author oldcrane<br/>
 * @created 2019-05-15
 */
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userDao;

	@Override
	public void insert(String loginName, String showName, String password) {
		UserDO user = new UserDO();
		// TODO loginName不能重复
		user.setLoginName(loginName);
		user.setShowName(showName);
		String salt = new SecureRandomNumberGenerator().nextBytes().toBase64();
		user.setSalt(salt);
		// TODO 添加密码校验规则
		String encryptedPwd = AuthHelper.encodePassphrase(password, salt);
		user.setPassword(encryptedPwd);
		LocalDateTime now = LocalDateTime.now();
		user.setActive(true);
		user.setGmtCreated(now);
		user.setGmtUpdated(now);

		userDao.insert(user);
	}

	@Override
	public void update(UserDO user) {
		UserDO dbUser = userDao.getById(user.getId());
		if (null != user.getShowName()) {
			dbUser.setShowName(user.getShowName());
		}
		if (null != user.getActive()) {
			dbUser.setActive(user.getActive());
		}
		dbUser.setGmtUpdated(LocalDateTime.now());
		userDao.update(dbUser);
	}

	@Override
	public UserDO getById(Integer id) {
		return userDao.getById(id);
	}

	@Override
	public UserDO getByLoginName(String loginName) {
		return userDao.getByLoginName(loginName);
	}

	@Override
	public List<UserDO> listAll(String keyword, Boolean active) {
		Map<String, Object> condition = new HashMap<>();
		if (null != keyword && keyword.trim().length() > 0) {
			condition.put("keyword", keyword.trim());
		}
		if (null != active) {
			condition.put("active", active);
		}
		return userDao.listAll(condition);
	}

	@Override
	public UserDO setPassword(Integer id, String newPassword) {
		UserDO user = userDao.getById(id);
		String salt = new SecureRandomNumberGenerator().nextBytes().toBase64();
		user.setSalt(salt);
		// TODO 添加密码校验规则
		String encryptedPwd = AuthHelper.encodePassphrase(newPassword, salt);
		user.setPassword(encryptedPwd);
		user.setGmtUpdated(LocalDateTime.now());
		userDao.update(user);
		return user;
	}

}
